package org.jeecg.config;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.safety.Whitelist;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lixingxing
 */
@Configuration
public class XssConfig {

    /**
     * xss白名单配置
     *
     * @return
     */
    @Bean
    public Whitelist whitelist() {
        Whitelist whitelist = Whitelist.relaxed();
        whitelist.preserveRelativeLinks(true);
        whitelist.addProtocols("img", "src", "https", "http");
        whitelist.addProtocols("a", "href", "https", "http");
        ClassPathResource resource = new ClassPathResource("whitelist.json");
        String whiteTags = resource.readUtf8Str();
        JSONObject obj = JSON.parseObject(whiteTags);
        obj.forEach((key, values) -> {
            whitelist.addTags(key);
            whitelist.addAttributes(key, obj.getJSONArray(key).stream().toArray(String[]::new));
        });
        return whitelist;
    }
}
